package com.link.base.base.agreement.service;

import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.agreement.dao.mybatis.mapper.AgreementMapper;
import com.link.base.base.agreement.model.Agreement;
import com.link.base.base.cmqres.model.CmqRes;
import com.link.base.base.cmqres.service.CmqResService;
import com.link.base.core.apiutils.ApiBeanUtils;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.mq.util.MqUtil;
import com.link.core.util.LovUtil;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author  unknwon
 * @date:   2018/11/8 10:47
 * @version 1.0
 */

@Service
public class AgreementServiceImpl extends BasicServiceImpl<Agreement> implements AgreementService {

    @Resource
    private AgreementMapper agreementMapper;

    @Resource
    private CmqResService cmqResService;

    @Resource
    private AccountService accountService;

    @Override
    public BasicMapper<Agreement> getBasicMapper() {
        return agreementMapper;
    }

    /**
     * 查询一条数据
     * @param entity
     * @return Agreement
     * @throws Exception
     */
    @Override
    public Agreement queryById(Agreement entity) throws Exception {
        Agreement agreement = null;
        Long entityId = entity.getId();
        try {
            if (null == entityId) {
                throw new ServiceException("PUBLIC-007");
            }
            Agreement param = new Agreement();
            param.setId(entityId);
            List<Agreement> entityList = queryAll(param);
            if (entityList.size() == 1) {
                agreement = entityList.get(0);
            } else if (entityList.size() == 0) {
                agreement = null;
            } else {
                throw new ServiceException("AGREEMENT-001！");
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new BasicServiceException(e.getMessage());
        }
        return agreement;
    }

    /**
     * 提交合同审批表
     * @param entity
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void submit(Agreement entity) throws Exception {
        Agreement validateObj = queryById(entity);
        if (validateObj == null) {
            throw new ServiceException("PUBLIC-032");
        }
        //获取独立源代码，用于逻辑判断
        String value = LovUtil.getLovValue("AGR_STATUS", validateObj.getAgrStatus());
        //新建
        String newStatus = "New";
        if (!StringUtils.isNull(value)) {
            //设置独立源代码，并代替了显示值
            validateObj.setAgrStatus(value);
        }
        if (!newStatus.equals(validateObj.getAgrStatus())) {
            throw new ServiceException("AGREEMENT-002",validateObj.getAgrStatus());
        }
        validateObj.setAgrStatus("Submitted");
        agreementMapper.agrStatusUpdate(validateObj);
    }

    @Override
    public List<Agreement> queryByContractCode(Agreement entity) throws Exception {
        return agreementMapper.queryByContractCode(entity);
    }


    @Override
    public void afterUpdate(Agreement agreement) throws Exception {
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if (cmqResList.size() > 0) {
            try {
                String message1 = "ContractsSyncl;{\"action\":\"Update\",\"objectId\":\"";
                String message2 = "\"}";
                String message = message1 + agreement.getId() + message2;
                String topicName = cmqResList.get(0).getQueueName();
                MqUtil.sendCmqTopic(topicName, message);
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }

    @Override
    public void afterInsert(Agreement agreement) throws Exception {
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if (cmqResList.size() > 0) {
            try {
                String message1 = "ContractsSyncl;{\"action\":\"Insert\",\"objectId\":\"";
                String message2 = "\"}";
                String message = message1 + agreement.getId() + message2;
                String topicName = cmqResList.get(0).getQueueName();
                MqUtil.sendCmqTopic(topicName, message);
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }

    /**
     * <p>检查该记录是否已存在，是则返回对象，否则返回null</p>
     * @author yrf
     * @param  model
     * @return Agreement
     * @throws Exception
     *
     */
    @Override
    public Agreement check(Agreement model) throws Exception {
        Long id = model.getCrmId();
        String integrationId = model.getIntegrationId();
        if (StringUtils.isBlank(integrationId)) {
            throw new ServiceException("AGREEMENT-003");
        }
        Agreement agreement = null;
        if (null == id) {
            // crmId 为空则根据集成Id查询
            Agreement example = new Agreement();
            example.setIntegrationId(integrationId);
            example.setPageFlag(false);
            List<Agreement> list = queryByExamplePage(example);
            if (list == null || list.size() == 0) {
                //nothing
            } else if (list.size() == 1) {
                agreement = list.get(0);
            } else {
                throw new ServiceException("AGREEMENT-004");
            }
        } else {
            Agreement example = new Agreement();
            example.setId(id);
            agreement = queryById(example);
            if (agreement == null) {
                throw new ServiceException("AGREEMENT-005",id.toString());
            } else if (!integrationId.equals(agreement.getIntegrationId())) {
                throw new ServiceException("AGREEMENT-006");
            }
        }
        return agreement;
    }

    /**
     * 校验客户
     *
     * @param acctId 客户ID
     */
    @Override
    public void checkAcct(Long acctId) throws Exception {
        if (null != acctId) {
            Account param = new Account();
            param.setId(acctId);
            Account account = accountService.queryById(param);
            if (account == null) {
                throw new ServiceException("AGREEMENT-007");
            }
        }

    }

    /**
     * 更新头行信息-interface用到
     * @param model
     * @return Agreement
     * @throws Exception
     */

    @Override
    public Agreement upsertHeadAndItem(Agreement model) throws Exception {
        checkAcct(model.getAccntId());
        Agreement agreement = check(model);
        if (agreement == null) {
            agreement = new Agreement();
            Long id = keyGenerateService.keyGenerate();
            ApiBeanUtils.copyProperties(model, agreement);
            agreement.setId(id);
            insert(agreement);
        } else {
            ApiBeanUtils.copyProperties(model, agreement);
            update(agreement);
        }
        return agreement;
    }

    /**
     * 批量更新头行信息-interface用到
     * @param list
     * @throws Exception
     */
    @Override
    public void batchUpsertHeadAndItem(List<Agreement> list) throws Exception {
        for (int i = 0; i < list.size(); i++) {
            Agreement model = list.get(i);
            upsertHeadAndItem(model);
        }
    }

}
